<template>
  <div class="app-container">
    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
    <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
  </div>
</template>

<script>
import { formatExcelDate } from '@/utils'
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { importEmployee } from '@/api/employee'
import moment from 'moment'
export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    // 本地文件上传之前的回调函数
    beforeUpload(file) {
      // 读取出来的数据的单位是bytes
      // 1mb=1024kb 1kb=1024bytes 1个英文是1bytes 一个汉字2-6个字节
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    // 本地文件上传成功触发的函数
    handleSuccess({ results, header }) {
      // 1.本地文件读取出js数据
      // 2.按后端格式更改
      // 3.发送携带格式化好的数据到后台服务器
      this.tableData = results
      this.tableHeader = header
      // 将代码中英文转化
      const renderlist = this.dataFormat(results)
      this.doadd(renderlist)
      console.log(renderlist, '中英文转化之后')
      console.log('results', results)
      console.log('header', header)
    },
    dataFormat(data) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      // 1.map方法映射数组
      const newlist = data.map(znobj => {
        // 2.利用空对象接收每次循环改变的值
        const newobj = {}
        Object.keys(mapInfo).forEach(
          cnkeys => {
            const enkeys = mapInfo[cnkeys]
            if (enkeys === 'timeOfEntry' || enkeys === 'correctionTime') {
              console.log('判断传值', 123)
              newobj[enkeys] = moment(new Date(formatExcelDate(znobj[cnkeys]))).format('YYYY-MM-DD')
            } else {
              newobj[enkeys] = znobj[cnkeys]
            }
            // 3.利用生成的键在中英转化数组里查找值,做新对象的键,
            // 再将键拿到znobj里面去作为键取值
            // 最后在新对象里里面变量新增属性
          }
        )
        return newobj
      })
      return newlist
    },
    // 批量导入数据
    async  doadd(data) {
      try {
        const res = await importEmployee(data)
        console.log(res)
        // if(res.code!==10000)return
        this.$router.back()
        console.log(res, '新增的数据')
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

